﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using DonnetSpeech;
using MINERP.BLL.Common;
using MINERP.BLL.PhotoRindGrid;
using MINERP.COM;
using MINERP.MODEL.FoundationModel;
using MINERP.PhotoRindGrid.Forms;
using MINERP.PhotoRindGrid.IView;
using System.Windows.Forms;
using GridView = MINERP.BLL.PhotoRindGrid.GridView;
using System.Data;
using FastReport;

using Timer = System.Windows.Forms.Timer;
using System.Diagnostics;
using MINERP.MODEL.PhotoRindGrid;
using FastReport.Export;
using System.Runtime.InteropServices;

namespace MINERP.PhotoRindGrid.Presenter
{
    public class MainPresenter
    {
        private PhotoRindGridBLL2 _bll;
        private IFrmPhotoRindGrid _view;
        public MainPresenter(IView.IFrmPhotoRindGrid view)
        {
            _view = view;
            _bll = new PhotoRindGridBLL2();

        }
        /// <summary>
        /// 绑定分区
        /// </summary>
        public void BingSubAreas()
        {
            if (_view.CurrSubares != null)
            {
                _bll.ChangeSubAreasUsed(_view.CurrSubares.SubAreaID, true);
            }

            List<GridSubArea_Info> subAreas = _bll.GetSubareaUseful();
            if (subAreas == null || subAreas.Count == 0)
            {

                //if (MessageBox.Show("当前没有可用分区", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information) == DialogResult.OK)
                //{
                //    //MINERP.COM.Logoff.ShowMainFrm();
                //    _view.Exit();
                //}
                //else
                ////{
                _view.Exit();
                //}
                //throw new Exception("无分区");
            }
            else if (subAreas.Count == 1)
            {
                _view.CurrSubares = subAreas[0];
            }
            else
            {
                _view.SelectSubArea(subAreas);
            }
            _bll.ChangeSubAreasUsed(_view.CurrSubares.SubAreaID, false);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public GridSubArea_Info GetOneSuAreaById(int subAreaId)
        {
            GridSubArea_Info info = _bll.GetOneSunAreaById(subAreaId);
            return info;
        }
        /// <summary>
        ///  显示所有格子
        /// </summary>
        public void ShowAllGrid()
        {

            List<GridView> gridViews = _bll.GetGridBySubAreaId(_view.CurrSubares.SubAreaID).OrderBy(p => Convert.ToInt32(p.GridName.Substring(1))).ToList();
            _view.ShowGrid(gridViews);
            SetSelectGridStyle(new UCGrid(), _view.CurrGrid);
        }
        /// <summary>
        /// 根据ID取得格子信息
        /// </summary>
        /// <param name="inGridId"></param>
        /// <returns></returns>
        public Grid_Info GetGridById(int inGridId)
        {
            return _bll.GetGridById(inGridId);
        }
        [DllImport("USER32.dll")]
        static extern short GetKeyState(int nVirtKey);
        const int VK_CONTROL = 0x11;
        /// <summary>
        /// 改变选中格子样式
        /// </summary>
        /// <param name="newGrid"></param>
        /// <param name="oldGrid"></param>
        public void SetSelectGridStyle(UCGrid newGrid, UCGrid oldGrid)
        {
            //if (oldGrid != null)
            //{
            //    if (((GetKeyState(VK_CONTROL) & 0x8000) == 0))//没有按下了CTRL键
            //    {
            //        oldGrid.BackColor = Color.White;
            //        oldGrid.BorderStyle = BorderStyle.FixedSingle;
            //    }

            //}
            //if (newGrid.ShopName == "")
            //{ }
            //else
            //{
            //    if (newGrid.BackColor == Color.Pink)
            //    {
            //        oldGrid.BackColor = Color.White;
            //        oldGrid.BorderStyle = BorderStyle.FixedSingle;
            //    }
            //    else
            //    {
            //        newGrid.BackColor = Color.Pink;
            //        newGrid.BorderStyle = BorderStyle.Fixed3D;
            //    }
            //}
            if (oldGrid == null && newGrid != null && !string.IsNullOrEmpty(newGrid.ShopName))
            {

                if (newGrid.BackColor == Color.Pink)
                {
                    newGrid.BackColor = Color.White;
                    newGrid.BorderStyle = BorderStyle.FixedSingle;
                }
                else
                {
                    newGrid.BackColor = Color.Pink;
                    newGrid.BorderStyle = BorderStyle.Fixed3D;
                }

            }
            else if (oldGrid != null && newGrid != null)
            {
                if (!string.IsNullOrEmpty(oldGrid.ShopName) && !string.IsNullOrEmpty(newGrid.ShopName))
                {
                    if (((GetKeyState(VK_CONTROL) & 0x8000) == 0))//没有按下了CTRL键
                    {
                        oldGrid.BackColor = Color.White;
                        oldGrid.BorderStyle = BorderStyle.FixedSingle;
                        newGrid.BackColor = Color.Pink;
                        newGrid.BorderStyle = BorderStyle.Fixed3D;
                    }
                    else
                    {

                        if (newGrid.BackColor == Color.Pink)
                        {
                            newGrid.BackColor = Color.White;
                            newGrid.BorderStyle = BorderStyle.FixedSingle;
                        }
                        else
                        {
                            newGrid.BackColor = Color.Pink;
                            newGrid.BorderStyle = BorderStyle.Fixed3D;
                        }

                    }

                }
                else if (!string.IsNullOrEmpty(oldGrid.ShopName) && string.IsNullOrEmpty(newGrid.ShopName))
                {


                    if (((GetKeyState(VK_CONTROL) & 0x8000) == 0))//没有按下了CTRL键
                    {
                        oldGrid.BackColor = Color.White;
                        oldGrid.BorderStyle = BorderStyle.FixedSingle;
                        newGrid.BackColor = Color.Pink;
                        newGrid.BorderStyle = BorderStyle.Fixed3D;

                    }
                    else
                    {

                    }


                }
                else if (string.IsNullOrEmpty(oldGrid.ShopName) && !string.IsNullOrEmpty(newGrid.ShopName))
                {
                    if (((GetKeyState(VK_CONTROL) & 0x8000) == 0))//没有按下了CTRL键
                    {
                        if (newGrid.BackColor != Color.Pink)
                        {
                            newGrid.BackColor = Color.Pink;
                            newGrid.BorderStyle = BorderStyle.Fixed3D;
                        }
                        if (oldGrid.BackColor == Color.Pink)
                        {
                            oldGrid.BackColor = Color.White;
                            oldGrid.BorderStyle = BorderStyle.FixedSingle;
                        }
                    }
                    else
                    {
                        if (oldGrid.BackColor == Color.Pink)
                        {
                            oldGrid.BackColor = Color.White;
                            oldGrid.BorderStyle = BorderStyle.FixedSingle;
                        }
                        if (newGrid.BackColor == Color.Pink)
                        {
                            newGrid.BackColor = Color.White;
                            newGrid.BorderStyle = BorderStyle.FixedSingle;
                        }
                        else
                        {
                            newGrid.BackColor = Color.Pink;
                            newGrid.BorderStyle = BorderStyle.Fixed3D;
                        }

                    }
                }
                else if (string.IsNullOrEmpty(oldGrid.ShopName) && string.IsNullOrEmpty(newGrid.ShopName))
                {

                    if (oldGrid.BackColor == Color.Pink)
                    {
                        oldGrid.BackColor = Color.White;
                        oldGrid.BorderStyle = BorderStyle.FixedSingle;
                    }
                    if (((GetKeyState(VK_CONTROL) & 0x8000) == 0))//没有按下了CTRL键
                    {
                        newGrid.BackColor = Color.Pink;
                        newGrid.BorderStyle = BorderStyle.Fixed3D;
                    }

                }
                else
                { }
            }
            else if (oldGrid != null && newGrid == null)
            {
                return;
            }
            else if (oldGrid == null && newGrid == null)
            {
                return;
            }
            ///判断是否过期
            if ((DateTime.Now - newGrid.FirstEnterTime).Minutes > _view.CurrSubares.OutTimeAlarmTime)
            {
                if (newGrid.ShopId != 0)
                {
                    newGrid.BackColor = Color.Red;
                }
            }

        }
        public void SetOldGridStyle(UCGrid oldGrid)
        {

            oldGrid.BackColor = Color.White;
            oldGrid.BorderStyle = BorderStyle.FixedSingle;

        }
        /// <summary>
        /// 右侧显示信息
        /// </summary>
        /// <param name="inGridId"></param>
        /// <returns></returns>
        public void DisplayShopInfo()
        {
            int gridId = _view.CurrGrid.GridId;
            int orderProductid = _view.CurrGrid.OrderId;
            //int gridId = _view.CurrentGrid.GridId;
            if (_view.CurrentGrid == null || _view.CurrentGrid.Status == (int)GridStatus.useAble)
            {
                return;
            }


            //_view.ShowGridInfo(_bll.GetShopInfo(gridId));
            PhotoGridOrderHeadInfo oihead = _bll.GetHeadInfo(orderProductid);
            oihead.GridName = _view.CurrGrid.GridName;
            _view.ShowGridInfo(oihead);
            _view.CurrPhotoList = _bll.GetPhotosByGrid(gridId);
            _view.ShowPhotoByGrid(_view.CurrPhotoList);

        }
        List<PhotoView> CurrPhotoList = new List<PhotoView>();
        /// <summary>
        /// 右侧显示未分配照片
        /// </summary>
        /// <param name="inGridId"></param>
        /// <returns></returns>
        public void DisplayShopInfoIamge()
        {
            int gridId = _view.CurrentGrid.GridId;
            if (_view.CurrentGrid.Status == (int)GridStatus.useAble)
            {
                return;
            }

            _view.ShowPhotoImage(_bll.GetPhotosByGrid(gridId));

        }
        public void ReceiveBarCode()
        {
            int outProductId = 0;

            int isReprint = _bll.IsRePrint(_view.CurrBarCode, _view.CurrTech, out outProductId);

            if (isReprint == 1)//产品是否已经完成
            {
                if (MessageBox.Show("该产品已完成，是否要打印小票", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
                {
                    DataSet ds = _bll.GetReportdata(0, outProductId, "");
                    ds.WriteXml(@"C:\windows\xmlData\PrintReport.xml", XmlWriteMode.WriteSchema);
                    Report fasrReport = new Report();
                    try
                    {
                        fasrReport.Load(Application.StartupPath + "\\frPhotoRindGrid.frx");
                    }
                    catch (Exception)
                    {

                        MessageBox.Show("加载报表失败", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

                    }
                    fasrReport.Print();
                }
            }
            else //未完成分配格子或者不存在
            {
                Assion();
            }
            //else if (isReprint == -1)
            //{
            //    //if (MessageBox.Show("该产品已完成，是否要打印小票", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
            //    //{
            //    //    DataSet ds = _bll.GetReportdataBK(0, outProductId, "");
            //    //    ds.WriteXml(@"C:\windows\xmlData\PrintReport.xml", XmlWriteMode.WriteSchema);
            //    //    Report fasrReport = new Report();
            //    //    try
            //    //    {
            //    //        fasrReport.Load(Application.StartupPath + "\\frPhotoRindGrid.frx");
            //    //    }
            //    //    catch (Exception)
            //    //    {

            //    //        MessageBox.Show("加载报表失败", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

            //    //    }
            //    //    fasrReport.Print();
            //    //}
            //    MessageBox.Show("产品已完成", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

            //}

        }
        int tryNum = 0;
        /// <summary>
        /// 分配格子
        /// </summary>
        public void Assion()
        {
            int intPhotoStatus = _bll.CheckPhoto(_view.CurrBarCode);
            if (intPhotoStatus == 1)//照片状态正常
            {
                int gridId = _bll.AssionGrid(_view.CurrBarCode, 1, _view.OperateUserId, _view.CurrSubares.SubAreaID, _view.CurrTech);//分配格子
                if (gridId == 0)//没有可用格子
                {
                    MessageBox.Show("分区没有可用格子", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                RushDisplayAndCheck(gridId);

            }
            else if (intPhotoStatus == -1)
            {

                MessageBox.Show("照片不存在,请检查产品是否完成", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;


            }
            else if (intPhotoStatus == -2)
            {
                MessageBox.Show("该产品在返工中！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            else if (intPhotoStatus == -3)
            {
                MessageBox.Show("当前照片未打印！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }


        }
        // FrmMessage frmMessage = new FrmMessage();

        /// <summary>
        /// 更新显示
        /// </summary>
        /// <param name="gridId"></param>
        private void RushDisplayAndCheck(int gridId)
        {

            //选中格子格式
            if (_view.CurrentGrid != null)
            {
                SetSelectGridStyle((UCGrid)_view.gridHash[gridId], (UCGrid)(_view.gridHash[_view.CurrentGrid.GridId]));
            }
            else
            {
                SetSelectGridStyle((UCGrid)_view.gridHash[gridId], null);
            }
            _view.CurrentGrid = _bll.GetGridById(gridId);
            int intCurr = _bll.GetCurrNum(gridId);

            _view.DisPlayGriName(_view.CurrentGrid.GridName);
            SpeechVoiceSpeakFlags SpFlags = SpeechVoiceSpeakFlags.SVSFlagsAsync;
            SpVoice Voice = new SpVoice();
            Voice.Speak(_view.CurrentGrid.GridName, SpFlags);




            OrderInfo_Info view = _bll.UpdateGrid(gridId);

            //((UCGrid)_view.gridHash[gridId]).labOrderName.Text = "产品名称:" + view.OrderProductName;
            ((UCGrid)_view.gridHash[gridId]).labProductName.Text = view.OrderProductName;
            ((UCGrid)_view.gridHash[gridId]).ShopName = view.ShopName;
            ((UCGrid)_view.gridHash[gridId]).OrderId = view.OrderProductId;
            ((UCGrid)_view.gridHash[gridId]).Curr = intCurr.ToString();
            bool isPrint = _bll.IsPrint(gridId, view.OrderProductId);

            if (isPrint)
            {

                //PrintGrid(_bll.OverCurrTech(_view.CurrTech, _view.OperateUserId, _view.CurrentGrid.SomeId));//当前流程结束激活下一个流程
                PrintGrid(_bll.OverCurrTech(_view.CurrTech, _view.OperateUserId, view.OrderProductId));//当前流程结束激活下一个流程

                _view.ClearGrid();


            }

        }
        //加急大板
        public void AdvanceBoard(int inNum)
        {
            _bll.AdvanceBoard(_view.CurrSubares.SubAreaID, inNum);
        }
        //加急格子
        public void AdvanceGrid(string inProductList)
        {
            _bll.AdvanceGrid(inProductList);
        }
        /// <summary>
        /// 清空格子
        /// </summary>
        public void ClearGrid()
        {
            if (MessageBox.Show("确认清空" + _view.CurrentGrid.GridName + "格子中的信息吗?", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information) == DialogResult.OK)
            {
                _bll.ClearGrid(_view.CurrentGrid.GridId, _view.CurrentGrid.SomeId);
                _view.ClearGrid();
            }

        }
        /// <summary>
        /// 恢复分区可用状态
        /// </summary>
        public void ChangeAreasUsed()
        {
            _bll.ChangeSubAreasUsed(_view.CurrSubares.SubAreaID, true);
        }
        public void PrintGrid()
        {
            //Stopwatch sp = new Stopwatch();
            //sp.Start();

            ////DataSet ds=_bll.GetReportdata(_view.CurrentGrid.GridId, _view.CurrentGrid.SomeId);
            //sp.Stop();
            //Console.WriteLine(sp.ElapsedMilliseconds);

            ///
            SpeechVoiceSpeakFlags SpFlags = SpeechVoiceSpeakFlags.SVSFlagsAsync;
            SpVoice Voice = new SpVoice();
            //sp.Reset();
            //sp.Start();
            string rtnStr = _bll.GetNextFlowName(_view.CurrentGrid.SomeId);
            //sp.Stop();
            //Console.WriteLine(sp.ElapsedMilliseconds);

            if (string.IsNullOrEmpty(rtnStr))
            {
                rtnStr = "此单已完成，此单为返工单，请再扫一次";
            }
            else
            {
                rtnStr = "此单已完成下一步" + rtnStr;
            }

            Voice.Speak(rtnStr, SpFlags);

            //if (rtnStr == null)
            //{
            //    Voice.Speak(_view.CurrentGrid.GridName + "格子已完成此单为，返工单", SpFlags);

            //}
            //else
            //{

            //    Voice.Speak(_view.CurrentGrid.GridName + "格子已完成下一步，" + rtnStr, SpFlags);
            //}

            //DataSet ds = _bll.GetReportdata(_view.CurrentGrid.GridId, _view.CurrentGrid.SomeId);
            DataSet ds = _bll.GetReportdata(_view.CurrentGrid.GridId, _view.CurrentGrid.SomeId, _view.CurrentGrid.GridName);
            ds.WriteXml(@"C:\windows\xmlData\PrintReport.xml", XmlWriteMode.WriteSchema);
            Report fasrReport = new Report();
            try
            {
                fasrReport.Load(Application.StartupPath + "\\frPhotoRindGrid.frx");
                fasrReport.Print();

                //fasrReport.Export(
                //fasrReport.Show();
            }
            catch (Exception)
            {

                MessageBox.Show("加载报表失败", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

            }


            //fasrReport.Show();
        }
        public void PrintGrid(string inNextTechName)
        {

            SpeechVoiceSpeakFlags SpFlags = SpeechVoiceSpeakFlags.SVSFlagsAsync;
            SpVoice Voice = new SpVoice();

            string rtnStr = inNextTechName;


            if ("InnerReturn".Equals(rtnStr))
            {
                rtnStr = "此单已完成，此单为返工单，请再扫一次";
            }
            else if ("error".Equals(rtnStr))
            {
                rtnStr = "此单不能正常完成，请检查";
            }
            else if (string.IsNullOrEmpty(rtnStr))
            {
                rtnStr = "返工单,请将此单与正常单放在一起！";
            }
            else
            {
                rtnStr = "完成，" + rtnStr;
            }

            Voice.Speak(rtnStr, SpFlags);

            DataSet ds = _bll.GetReportdata(_view.CurrentGrid.GridId, _view.CurrentGrid.SomeId, _view.CurrentGrid.GridName);

            string orderRemark = ds.Tables["infoTable"].Rows[0]["remark"].ToString();
            string ProuctName = ds.Tables["infoTable"].Rows[0]["OrderProductName"].ToString();

            if (orderRemark.Contains("淋膜")||ProuctName.Contains("淋膜"))
            {
                Voice.Speak("单淋膜", SpFlags);
            }
            else if (orderRemark.Contains("冷裱")||ProuctName.Contains("冷裱"))
            {
                Voice.Speak("单冷裱", SpFlags);
            }            

            ds.WriteXml(@"C:\windows\xmlData\PrintReport.xml", XmlWriteMode.WriteSchema);
            Report fasrReport = new Report();
            try
            {
                fasrReport.Load(Application.StartupPath + "\\frPhotoRindGrid.frx");
                fasrReport.Print();

            }
            catch (Exception)
            {

                MessageBox.Show("加载报表失败", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

            }


        }
        /// <summary>
        /// 强制打印
        /// </summary>
        public void PrePrint()
        {

            if (_bll.checkIsCurraTech(_view.CurrentGrid.SomeId, _view.CurrTech))
            {
                _bll.ClearGrid(_view.CurrentGrid.GridId, _view.CurrentGrid.SomeId);
                _bll.CompleteGridPhoto(_view.CurrentGrid.GridId, _view.CurrentGrid.SomeId);///改变格子的照片状态
                _bll.OverCurrTech(_view.CurrTech, _view.OperateUserId, _view.CurrentGrid.SomeId);//当前流程结束激活下一个流程
                PrintGrid();
                _view.ClearGrid();
            }
            else
            {
                MessageBox.Show("产品还未打印完毕，不能强制打印！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
        public string GetShopNameByOrderId(int inOrderid)
        {
            return _bll.GetShopNameByOrderId(inOrderid);
        }

    }
}
